<template>
  <div>
    <el-dialog
      v-model="props.visible"
      title="生产单列表"
      width="80%"
      @close="handleCancel"
    >
      <el-form
        :model="queryParams"
        class="flex-box"
        ref="queryRef"
        :inline="true"
      >
        <div>
          <el-form-item label="生产单编码" prop="produceNo">
            <el-input
              v-model.trim="queryParams.produceNo"
              placeholder="请输入生产单编码"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </div>
        <el-button
          type="primary"
          plain
          @click="handleSubmit"
          :disabled="multiple"
        >
          确认
        </el-button>
      </el-form>
      <el-row :gutter="20" style="overflow: auto">
        <el-col :span="8">
          <el-table
            v-loading="loading"
            :data="orderList"
            stripe
            border
            style="cursor: pointer"
            @cell-click="handleClick"
            ref="orderListTable"
            highlight-current-row
          >
            <el-table-column
              label="序号"
              width="55"
              type="index"
              align="center"
            />
            <el-table-column
              label="生产单编码"
              align="center"
              prop="produceNo"
            ></el-table-column>
            <el-table-column label="下单日期" align="center" prop="submitDate">
              <template v-slot="{ row }">
                {{ row.submitDate ? row.submitDate.split("T")[0] : "" }}
              </template>
            </el-table-column>
            <el-table-column label="类型" align="center" prop="type">
              <template v-slot="{ row }">
                <el-tag :type="row.type == 1 ? 'success' : ''" effect="dark">
                  {{ row.type == 1 ? "封面" : "内文" }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="16">
          <el-table
            ref="orderRef"
            v-loading="loadingInfo"
            :data="paperList"
            row-key="pieceId"
            stripe
            border
            style="cursor: pointer"
            height="420px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              :reserve-selection="true"
              width="55"
            />
            <el-table-column
              label="序号"
              width="55"
              type="index"
              align="center"
            />
            <el-table-column
              label="书刊名称"
              min-width="200"
              align="center"
              prop="bookName"
            ></el-table-column>
            <el-table-column
              label="品种"
              align="center"
              prop="breedType"
            ></el-table-column>

            <el-table-column
              label="书刊编码"
              align="center"
              prop="bookNo"
            ></el-table-column>
            <el-table-column
              label="贴标"
              align="center"
              prop="pieceView"
            ></el-table-column>
            <el-table-column label="印刷方式" align="center" prop="printType">
              <template #default="scope">
                <dict-tag
                  :options="mes_paper_package"
                  :value="scope.row.printType"
                />
              </template>
            </el-table-column>
            <el-table-column label="印色" align="center" prop="printColor">
              <template #default="scope">
                <dict-tag
                  :options="ems_order_print_color"
                  :value="scope.row.printColor"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="印张"
              align="center"
              prop="sheet"
            ></el-table-column>
            <el-table-column
              label="印数"
              align="center"
              prop="printAmount"
            ></el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <div class="footer">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { toNumber } from "@/utils/ruoyi";
import { orupdateList } from "@/api/production/standard.js";
import {
  getProduceOrderList,
  getProduceById,
  GetProducelistByMachineId,
  GetProducelistYQBByMachineId,
  getByIdFilter,
} from "@/api/production/cover";
import Index from "../standard/index.vue";
import { registerLoading } from "echarts";
const emit = defineEmits(["changeUpdate", "cancel"]);
const { proxy } = getCurrentInstance();
const { mes_paper_package, ems_order_print_color } = proxy.useDict(
  "mes_paper_package",
  "ems_order_print_color"
);

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  orderSelectList: {
    type: Array,
    default: () => {
      [];
    },
  },
  params: {
    type: Object,
    default: () => {
      {
      }
    },
  },
});

const orderRef = ref(null);
const orderList = ref([]);
const paperList = ref([]);
const multiple = ref(true);
const selectRow = ref([]);
const loading = ref(false);
const loadingInfo = ref(false);
const orderListTable = ref(null);
const standardList = ref([]);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  status: "5,6,7,8,9,10,11,12,13,14,15,16,17,18",
});
watch(
  () => props.visible,
  (val) => {
    if (val) {
      handleQuery();
      nextTick(() => {
        orderRef.value.clearSelection();
        if (props.orderSelectList.length > 0) {
          props.orderSelectList.forEach((item) => {
            orderRef.value.toggleRowSelection(item, true);
          });
        }
      });
    }
  }
);
const total = ref(0);
// 选中订单
const handleClick = (row) => {
  //debugger
  loadingInfo.value = true;
  getByIdFilter({
    produceId: row.produceId,
    machineId: props.params.machineId,
  }).then((res) => {
    res.data.producePieceList.forEach((item) => {
      item.orderTime = res.data.submitDate;
      item.produceCode = res.data.produceNo;
      item.type = res.data.type;
      res.data.producePrintList.forEach((ele) => {
        if (item.printId == ele.printId) {
          // 最大上报量 = 印数+ 另行加放
          // item.maxNum = Number(ele.printAmount) + Number(ele.lxjf)
          //  印刷数*（1+损耗系数）
          //   item.maxNum = toNumber(
          //     Number(ele.printAmount) * (1 + Number(ele.lossCoefficient || 0))
          //   );
          item.tonnageCoefficient = ele.tonnageCoefficient; // 吨位系数
          // item.lxjf = ele.lxjf;
          //20240618 平张：完成数量=印数*印张 卷筒：完成数量=印数
          if (item.printType == 1) {
            item.finishNum =
              Number(ele.printAmount || 0) * Number(item.sheet || 0);
          } else {
            item.finishNum = Number(ele.printAmount || 0);
          }
          // //20240617 完成数量=印数
          // item.finishNum=ele.printAmount;
          //20240608
          // if (item.printType == 1) {
          //   //平张
          //   //平张 完成工作量=(印数：printAmount * 印张：sheet*（1+损耗系数：lossCoefficient）+另行加放:lxjf）
          //   //向上取整 Math.ceil  向下取整：Math.floor
          //   item.finishNum = Math.floor(
          //     Number(ele.printAmount || 0) *
          //       Number(item.sheet || 0) *
          //       (1 + Number(ele.lossCoefficient || 0)) +
          //       Number(ele.lxjf || 0)
          //   ); //item.maxNum;
          //   item.BJCount =
          //     Number(ele.printAmount || 0) * Number(item.sheet || 0);
          // } else if (item.printType == 2) {
          //   //卷筒
          //   //卷筒 完成工作量=(印数：printAmount *（1+损耗系数：lossCoefficient）+另行加放:lxjf）
          //   item.finishNum = Math.floor(
          //     Number(ele.printAmount || 0) *
          //       (1 + Number(ele.lossCoefficient || 0)) +
          //       Number(ele.lxjf || 0)
          //   ); //item.maxNum;
          //   item.BJCount = Number(ele.printAmount || 0);
          // }
          // if (item.printType == 2) {
          //   item.expectLing = toNumber(
          //     (Number(item.finishNum || 0) * Number(item.sheet || 0)) / 1000,
          //     4
          //   );
          // } else {
          //   item.expectLing = toNumber(Number(item.finishNum || 0) / 1000, 4);
          // }
          /***20240621
           * 预计用纸=实际用纸：
           *  封面：（印数+另行加放）（1+损耗系数）/1000
           *  内文：印数（1+损耗系数）*印张/1000+另行加放
           */
          if (row.type == 1) {
            item.multipleReport = "1";
            // 封面
            item.expectLing = toNumber(
              ((Number(item.printAmount || 0) + Number(item.lxjf || 0)) *
                (1 + Number(item.lossCoefficient || 0))) /
                1000,
              4
            );
          } else {
            // 内文
            if (ele.printColourType == 3) {
              // 是否多次报工 0 否 1 是
              item.multipleReport = "0";
              // 正背印 键值3
              item.printColourType = ele.printColourType;
            } else {
              item.multipleReport = "1";
            }
            if (ele.isQk == 1) {
              item.expectLing = toNumber(
                (Number(item.printAmount || 0) *
                  (1 + Number(item.lossCoefficient || 0)) *
                  Number(item.sheet || 0)) /
                  1000 +
                  (ele.printType == 1
                    ? Number(item.lxjf || 0)
                    : Number(item.lxjf || 0) *
                      Number(item.tonnageCoefficient || 0)),
                4
              );
            } else {
              item.expectLing = toNumber(
                (Number(item.printAmount || 0) *
                  (1 + Number(item.lossCoefficient || 0)) *
                  Number(item.sheet || 0)) /
                  500 +
                  (ele.printType == 1
                    ? Number(item.lxjf || 0)
                    : Number(item.lxjf || 0) *
                      Number(item.tonnageCoefficient || 0)),
                4
              );
            }
          }

          //20240617 令数=完成数量/1000 如果小于1，则等于1
          item.pieceLing = toNumber(Number(item.finishNum || 0) / 1000, 4);
          if (item.multipleReport == "1") {
            if (item.pieceLing < 1) {
              item.pieceLing = 1;
            }
          }

          //0608 修改
          // item.pieceLing = toNumber(
          //   (Number(item.finishNum || 0) / 1000) ,
          //   4
          // );
          //item.pieceLing <1 ? 1 : item.pieceLing
          //1、印数大于等于1000，按照 “完成工作量/1000”计算
          //2、印数小于1000，需要判断完成量*0.99>=印数 =1
          //<1按照 “（完成工作量/1000”计算
          // if (
          //   item.finishNum < 1000 &&
          //   Number(item.totalNum || 0) + Number(item.finishNum || 0) >=
          //     0.99 * item.BJCount
          // ) {
          //   item.SYNum = Number(item.finishNum || 0) - Number(item.maxNum || 0); //剩余数量
          //   item.SYNum = item.SYNum < 0 ? 0 : item.SYNum;
          //   item.pieceLing = toNumber(1 - item.SYNum / 1000, 4);
          //   if (item.printType == 2 && item.pieceLing < 1) {
          //     item.pieceLing = 1;
          //   }
          // } else {
          //   // 完工数量/1000 * 印张
          //   item.pieceLing = toNumber(Number(item.finishNum || 0) / 1000, 4);
          // }

          item.exchangeNum = 2;
          item.realityLing = item.expectLing;
          item.ykLing = 0;
          if (res.data.type == 1) {
            // 封面
            item.printColor = res.data.producePrintList[0]?.printColour;
            res.data.produceProductList.forEach((obj) => {
              if (ele.orderProductId === obj.orderProductId) {
                item.pubNo = obj.pubNo;
              }
            });
          } else {
            res.data.produceProductList.forEach((obj) => {
              if (ele.orderProductId === obj.orderProductId) {
                item.printColor = obj.printColor;
                item.pubNo = obj.pubNo;
              }
            });
          }
          item.lossCoefficient = ele.lossCoefficient; // 损耗系数
          item.tonnageCoefficient = ele.tonnageCoefficient; // 吨位系数
          item.bookName = ele.bookName;
          item.breedType = ele.breed;
          item.bookNo = ele.bookNo;
          item.printAmount = ele.printAmount;
        }
      });
    });
    paperList.value = res.data.producePieceList;
    loadingInfo.value = false;
  });
};

const getOrupdateList = () => {
  orupdateList({ pageNum: 1, pageSize: 100, technologyType: 1 }).then((res) => {
    standardList.value = res.rows;
  });
};
getOrupdateList();
function extractTextInBrackets(str) {
  // 正则表达式匹配括号内的内容，包括可能的多个括号嵌套
  var regex = /\(([^()]*)\)/;
  var match = str.match(regex);
  // 返回匹配到的第一个括号内的内容，如果没有匹配项则返回null
  return match ? match[1] : null;
}

// 选中
const handleSelectionChange = (row) => {
  //debugger
  selectRow.value = row;
  selectRow.value.forEach((item) => {
    standardList.value.forEach((obj) => {
      if (item.type == 1) {
        // 封面
        if (obj.machineType.includes("(")) {
          if (
            extractTextInBrackets(obj.machineType) ==
            findPrintColor(item.printColor)
          ) {
            // 计件标准 pieceStandard
            // 工作内容
            if (obj.workContent == 1) {
              // 印刷
              item.standard = obj.pieceStandard;
            } else {
              // 换版
              item.standardH = obj.pieceStandard;
            }
          }
        }
      } else {
        // 内文
        if (item.printType == 1) {
          if (obj.machineType.includes("(")) {
            if (
              extractTextInBrackets(obj.machineType) ==
              findPrintColor(item.printColor)
            ) {
              // 计件标准 pieceStandard
              // 工作内容
              if (obj.workContent == 1) {
                // 印刷
                item.standard = obj.pieceStandard;
              } else {
                // 换版
                item.standardH = obj.pieceStandard;
              }
            }
          }
        } else {
          if (obj.machineType.includes("-")) {
            if (obj.machineType.split("-")[1] == item.wagesType) {
              item.standard = obj.pieceStandard;
            }
          } else if (obj.machineType == "轮转") {
            item.standardH = obj.pieceStandard;
          }
          // 需获取单色道还是双色道
        }
      }
    });
  });
  multiple.value = !row.length;
};
function findPrintColor(val) {
  return ems_order_print_color.value.filter((item) => item.value == val)[0]
    .label;
}
const handleSubmit = () => {
  selectRow.value.forEach((item) => {
    // 平板双色（1030）3号机  // 平板双色（1030）4号机  //平板双色（1030）5号机 //平板双色（1030）6号机  // 四色（930）1号机
    // 计件标准8块
    if (
      props.params.machineId == "e871014ac4054f2888e089d05ae9c36a" ||
      props.params.machineId == "5bfd2e94fa6d44b3bc4ff2ce4287346b" ||
      props.params.machineId == "36644751392845bf83e641da597d0b8c" ||
      props.params.machineId == "39ad48d4a280400b8abe6fd9054d5421" ||
      props.params.machineId == "b8a5b7fecaaf440e94e7e96d9097ca7b"
    ) {
      item.standard = 8;
    } else if (props.params.machineId == "e6f5f7d8bd784d738e9d0b2c12b963ae") {
      //  八色（1030）SM1号机 9块
      item.standard = 9;
    } else if (props.params.machineId == "de30779372a24043967df6f8b0b375f4") {
      // 八色（1055）XL1号机
      item.standard = 12;
    }
    // 八色（1030）SM1号机、八色（1055）XL1号机
    if (
      props.params.machineId == "e6f5f7d8bd784d738e9d0b2c12b963ae" ||
      props.params.machineId == "de30779372a24043967df6f8b0b375f4"
    ) {
      item.exchangeNum = 8;
      item.pieceLing = toNumber(Number(item.finishNum || 0) / 1000, 4);
    } else if (props.params.machineId == "b8a5b7fecaaf440e94e7e96d9097ca7b") {
      // 四色（930）1号机
      item.pieceLing = toNumber(Number(item.finishNum || 0) / 1000, 4);
      item.exchangeNum = 4;
    }
  });

  emit("changeUpdate", selectRow.value);
};
const handleCancel = () => {
  paperList.value = [];
  proxy.resetForm("queryRef");
  emit("cancel");
};
const getList = async () => {
  loading.value = true;
  const res = await GetProducelistYQBByMachineId({
    ...queryParams.value,
    ...props.params,
  });
  orderListTable.value.setCurrentRow(res.rows[0]);
  loading.value = false;
  orderList.value = res.rows;
  if (orderList.value.length > 0) {
    handleClick(orderList.value[0]);
  } else {
    paperList.value = [];
  }
  total.value = res.total;
};
// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryRef");
  handleQuery();
};

// getList()
</script>

<style lang="scss" scoped></style>
